<!-- 管理 -->
<template>
  <div class="app-container">
    <el-row :gutter="20" mt-3>
      <el-col :span="7">
        <el-card>
          <el-calendar ref="calendar">
            <template #header="{ date }">
              <el-button
                type="primary"
                @click="openDialog()"
                icon="plus"
                circle
                style="margin-top: -5px"
              />
              <span>{{ date }}</span>
              <el-button-group>
                <el-button size="small" @click="selectDate('prev-month')">
                  <el-icon><DArrowLeft /></el-icon>
                </el-button>
                <el-button size="small" @click="selectDate('today')"
                  >今天</el-button
                >
                <el-button size="small" @click="selectDate('next-month')">
                  <el-icon><DArrowRight /></el-icon>
                </el-button>
              </el-button-group>
            </template>
            <template #date-cell="{ data }">
              {{ data.day.split("-").slice(1)[1] }}
              <span v-for="item in calendarOptions.events" :key="item.id">
                <div
                  v-if="
                    new Date(data.day).getDate() >=
                      new Date(item.start).getDate() &&
                    new Date(data.day).getMonth() ==
                      new Date(item.start).getMonth() &&
                    new Date(data.day).getDate() <= new Date(item.end).getDate()
                  "
                  class="el-calendar-day-current-c"
                  :style="{ backgroundColor: item.color }"
                ></div>
              </span>
            </template>
          </el-calendar>
        </el-card>
      </el-col>
      <el-col :span="17">
        <el-card>
          <FullCalendar :options="calendarOptions">
            <template #eventContent="arg">
              <el-popover
                :width="300"
                popper-style="box-shadow: rgb(14 18 22 / 35%) 0px 10px 38px -10px, rgb(14 18 22 / 20%) 0px 10px 20px -15px; padding: 20px;"
              >
                <template #reference>
                  <el-avatar
                    size="small"
                    :src="arg.event.extendedProps.avatar"
                  />
                </template>
                <template #default>
                  <div
                    style="
                      width: 100%;
                      background: #336df2d9;
                      position: absolute;
                      top: 0;
                      left: 0;
                      padding: 15px;
                      display: flex;
                      align-items: center;
                      justify-content: left;
                    "
                  >
                    <el-avatar
                      :size="48"
                      :src="arg.event.extendedProps.avatar"
                      style="margin-bottom: 8px"
                    /><span
                      style="color: var(--el-color-white); margin-left: 5px"
                    >
                      {{ arg.event.extendedProps.nickname }}
                    </span>
                  </div>
                  <div
                    style="
                      border-left: 5px solid green;
                      padding: 5px;
                      margin-top: 35%;
                    "
                    :style="{
                      'border-left':
                        arg.event.extendedProps.is_handle == -1
                          ? '5px solid red'
                          : '5px solid green',
                    }"
                  >
                    {{
                      arg.event.extendedProps.is_handle == 0
                        ? "未开始"
                        : "已完成"
                    }}<span style="float: right; font-weight: 500">{{
                      arg.event.allDay == true
                        ? "全天"
                        : formatTimer(arg.event.start)
                    }}</span>
                  </div>

                  <p style="font-weight: 500">{{ arg.event.title }}</p>
                  <p
                    v-show="arg.event.extendedProps.remark"
                    class="demo-rich-content__desc"
                    style="
                      margin: 0;
                      color: var(--el-color-info);
                      margin-bottom: 10px;
                    "
                  >
                    {{ arg.event.extendedProps.remark }}
                  </p>
                  <el-divider v-show="arg.event.extendedProps.is_owner == 1" />
                  <div
                    v-show="arg.event.extendedProps.is_owner == 1"
                    style="text-align: right"
                  >
                    <el-button
                      type="primary"
                      @click="openDialog(arg.event.id)"
                      icon="Edit"
                      circle
                    />
                    <el-button type="success" icon="Check" circle />
                    <el-button
                      type="danger"
                      @click="handleDelete(arg.event.id)"
                      icon="Delete"
                      circle
                    />
                  </div>
                </template>
              </el-popover>
              <div
                v-show="
                  arg.event.extendedProps.is_handle == 0 &&
                  arg.event.extendedProps.is_range == 0
                "
                style="
                  border-left: 6px solid var(--el-color-primary);
                  width: 5px;
                  margin-left: 4px;
                  z-index: 999;
                "
              >
                &nbsp;
              </div>
              <div
                v-show="
                  arg.event.extendedProps.is_handle == 1 &&
                  arg.event.extendedProps.is_range == 0
                "
                style="
                  border-left: 6px solid var(--el-color-success);
                  width: 5px;
                  margin-left: 4px;
                  z-index: 999;
                "
              >
                &nbsp;
              </div>
              <div
                v-show="
                  arg.event.extendedProps.is_handle == -1 &&
                  arg.event.extendedProps.is_range == 0
                "
                style="
                  border-left: 6px solid var(--el-color-danger);
                  width: 5px;
                  margin-left: 4px;
                  z-index: 999;
                "
              >
                &nbsp;
              </div>
              <span style="margin-left: 2px" class="ellipsis"
                >{{
                  arg.event.allDay == true
                    ? "全天"
                    : formatTimer(arg.event.start)
                }}
                {{ arg.event.title }}</span
              >
              <el-icon style="position: absolute; right: 10px; font-size: 26px"
                ><CircleCheck
                  color="green"
                  v-show="
                    arg.event.extendedProps.is_handle == 1 &&
                    arg.event.extendedProps.category_type == 2
                  " /><CircleClose
                  color="red"
                  v-show="
                    arg.event.extendedProps.is_handle == -1 &&
                    arg.event.extendedProps.category_type == 2
                  " /><svg-icon
                  icon-class="unchecked"
                  v-show="
                    arg.event.extendedProps.is_handle == 0 &&
                    arg.event.extendedProps.category_type == 2
                  "
              /></el-icon>
            </template>
          </FullCalendar>
        </el-card>
      </el-col>
    </el-row>

    <!-- 弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialog.width"
      append-to-body
      @close="closeDialog"
    >
      <!-- 新增/编辑表单 -->
      <el-form
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="名称" prop="title">
          <el-input v-model="formData.title" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="时间" prop="time">
          <el-date-picker
            v-model="formData.start_time"
            type="datetime"
            placeholder="开始时间"
            format="YYYY-MM-DD HH:mm:ss"
            date-format="MM-DD, YYYY"
            time-format="HH:mm"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
          <span class="text-gray-500" style="margin: 5px"> - </span>
          <el-date-picker
            v-model="formData.end_time"
            type="datetime"
            placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            date-format="MM-DD, YYYY"
            time-format="HH:mm"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="优先级" prop="type">
          <el-select v-model="formData.type" placeholder="请选择优先级">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="category_type">
          <el-select v-model="formData.category_type" placeholder="请选择类型">
            <el-option key="1" label="提醒" :value="1" />
            <el-option key="2" label="任务" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="日程颜色" prop="color">
          <el-color-picker
            v-model="formData.color"
            show-alpha
            color-format="hex"
            :predefine="predefineColors"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            v-model="formData.remark"
            placeholder="请输入备注信息"
          />
        </el-form-item>
        <el-form-item label="是否公开" prop="is_public">
          <el-radio-group v-model="formData.is_public">
            <el-radio-button label="公开" :value="1" />
            <el-radio-button label="私密" :value="0" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="is_hid">
          <el-radio-group v-model="formData.is_hid">
            <el-radio :value="0">正常</el-radio>
            <el-radio :value="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "WorkCalendar",
  inheritAttrs: false,
});
import type { CalendarDateType, CalendarInstance } from "element-plus";
import FullCalendar from "@fullcalendar/vue3";
import dayGridPlugin from "@fullcalendar/daygrid";
import timeGridPlugin from "@fullcalendar/timegrid";
import listPlugin from "@fullcalendar/list";
import interactionPlugin from "@fullcalendar/interaction";
import {
  getSchedulePage,
  addSchedule,
  updateSchedule,
  getScheduleForm,
  deleteSchedule,
  getOptions,
} from "@/api/schedules";
import {
  ScheduleForm,
  ScheduleQuery,
  SchedulePage,
  ScheduleOptions,
} from "@/api/schedules/types";
const calendar = ref<CalendarInstance>();
const selectDate = (val: CalendarDateType) => {
  if (!calendar.value) return;
  calendar.value.selectDate(val);
};
const calendarOptions = ref({
  height: 720,
  locale: "zh",
  timeZone: "UTC",
  plugins: [dayGridPlugin, timeGridPlugin, listPlugin, interactionPlugin],
  eventDurationEditable: true,
  themeSystem: "#fff",
  allDayText: "全天",
  allDaySlot: true,
  buttonText: {
    // 设置按钮
    month: "月",
    week: "周",
    day: "天",
    list: "周列表",
  },
  headerToolbar: {
    //日历头部
    left: "prev,next",
    center: "title",
    right: "dayGridMonth,timeGridWeek,timeGridDay,listWeek",
  },
  initialView: "dayGridMonth",
  allDaySlot: true,
  dayMaxEventRows: 3,
  nowIndicator: true,
  events: [],
  eventClick: function (event) {},
  eventMouseEnter: function (event) {},
  eventMouseLeave: function (event) {},
});
const options = ref<ScheduleOptions[]>(); // 下拉数据源
const queryFormRef = ref(ElForm); // 查询表单
const userFormRef = ref(ElForm); // 表单
const isShowSearchBtn = ref(false);
const isShowForm = ref(false);
const loading = ref(false); //  加载状态
const removeIds = ref([]); // 删除ID集合 用于批量删除
const queryParams = reactive<ScheduleQuery>({
  p: 1,
  limit: 10,
});
const pageData = ref<SchedulePage[]>(); // 分页数据
// 弹窗对象
const predefineColors = ref([
  "#336DF2",
  "#3FC2F7",
  "#4752E8",
  "#7B36F1",
  "#BD3FBD",
  "#8D969F",
  "#E158A6",
  "#F74B47",
  "#FF811A",
  "#FDC60A",
  "#34BD4B",
  "#33D6C1",
]);
const dialog = reactive({
  visible: false,
  type: "user-form",
  width: 800,
  title: "",
});
// 表单数据
const formData = reactive<ScheduleForm>({
  is_hid: 0,
  is_public: 1,
  color: "#336DF2D9",
});
// 校验规则
const rules = reactive({
  title: [{ required: true, message: "名称不能为空", trigger: "blur" }],
  start_time: [
    { required: true, message: "开始时间不能为空", trigger: "blur" },
  ],
  category_type: [{ required: true, message: "类型不能为空", trigger: "blur" }],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  getSchedulePage(queryParams)
    .then(({ data }) => {
      calendarOptions.value.events = data.items.map((item: any) => {
        return {
          id: item.id,
          title: item.title,
          start: item.start_time,
          end: item.end_time,
          className: "fullcalendar-radius",
          color: item.color,
          avatar: item.avatar,
          category_type: item.category_type,
          is_handle: item.is_handle,
          is_range: item.is_range,
          is_owner: item.is_owner,
          remark: item.remark,
          nickname: item.nickname,
        };
      });
    })
    .finally(() => {
      loading.value = false;
    });
}

async function loadOptions() {
  getOptions().then((response) => {
    options.value = response.data;
  });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.p = 1;
  handleQuery();
}

/** 行选中 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

function cascaderCheck(data: any) {
  if (data.length > 0) {
    formData.pid = data[data.length - 1];
  } else {
    formData.pid = 0;
  }
}

/**
 * 打开弹窗
 *
 * @param id
 */
async function openDialog(id?: number) {
  dialog.visible = true;
  await loadOptions();
  console.log(id);
  // 表单弹窗
  if (id) {
    dialog.title = "修改";
    getScheduleForm(id).then(({ data }) => {
      Object.assign(formData, { ...data });
    });
  } else {
    dialog.title = "新增";
  }
}

/**
 * 关闭弹窗
 */
function closeDialog() {
  dialog.visible = false;
  userFormRef.value.resetFields();
  userFormRef.value.clearValidate();

  formData.id = undefined;
  formData.is_hid = 0;
  formData.start_time = undefined;
  formData.end_time = undefined;
  handleQuery();
}

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  userFormRef.value.validate((valid: any) => {
    loading.value = true;
    if (valid) {
      const ids = formData.id;
      if (ids) {
        updateSchedule(formData)
          .then(() => {
            ElMessage.success("修改成功");
            closeDialog();
          })
          .finally(() => (loading.value = false));
      } else {
        addSchedule(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleQuery();
            closeDialog();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 3000);

/** 删除用户 */
function handleDelete(id?: number) {
  const ids = id || removeIds.value;
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    deleteSchedule({ ids: ids }).then(() => {
      handleQuery();
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}

function formatTimer(value) {
  let date = new Date(value);
  let y = date.getFullYear();
  let MM = date.getMonth() + 1;
  MM = MM < 10 ? "0" + MM : MM;
  let d = date.getDate();
  d = d < 10 ? "0" + d : d;
  let h = date.getHours();
  h = h < 10 ? "0" + h : h;
  let m = date.getMinutes();
  m = m < 10 ? "0" + m : m;
  let s = date.getSeconds();
  s = s < 10 ? "0" + s : s;
  return h + ":" + m;
}

//收起展开搜索按钮
function handleSearchShowBtn() {
  isShowSearchBtn.value = isShowSearchBtn.value === false;
}

function categoryType(value: any) {
  isShowForm.value = value == 2;
}

onMounted(() => {
  handleQuery();
});
</script>

<style lang="scss" scoped>
::v-deep(.el-calendar-day) {
  padding: 8px 2px 2px;
  height: 40px;
  text-align: center;
  font-size: 12px;
  position: relative;
  .el-calendar-day-current-c {
    width: 10px;
    height: 10px;
    border-radius: 10px;
    display: inline-block;
    position: absolute;
    bottom: 2px;
    right: 42%;
    border: 0;
  }
}
::v-deep(.fc) {
  .fc-event-main,
  .fc-list-event-title {
    display: flex;
    align-items: center;
    border-bottom: 0;
  }
  color: var(--text-color);
  .fc .fc-icon-chevron-left {
    color: var(--text-color);
  }
  .fc-col-header-cell {
    padding: 12px 0;
    color: var(--el-text-color-regular);
    font-weight: 400;
  }
  .fc-button-primary:focus,
  .fc-button-primary:not(:disabled).fc-button-active:focus,
  .fc-button-primary:not(:disabled):active:focus {
    box-shadow: 0 0 0 0;
    border: var(--el-border);
    color: var(--el-button-text-color);
  }
  // 操作按钮
  .fc-button {
    border-radius: 0.95em;
    background-color: var(--el-button-bg-color) !important;
    color: var(--el-button-text-color);
    border: var(--el-border);
    padding: 0.4em 0.95em;
    font-size: 14px;
  }
  .fc-button.fc-button-active,
  .fc .fc-button-primary:hover {
    --el-button-text-color: var(--el-color-white) !important;
    --el-button-bg-color: var(--el-color-primary) !important;
    --el-button-border-color: var(--el-color-primary) !important;
    border: var(--el-border);
  }
  .fc .fc-button:active {
    border: none !important;
    box-shadow: 0 0 0 0 !important;
  }
  .fc .fc-button:focus {
    border: none !important;
    box-shadow: 0 0 0 0 !important;
  }
  .fc-col-header-cell.fc-day {
    color: var(--text-color);
  }
  // 时间文字
  .fc-toolbar-title {
    color: var(--text-color);
    text-align: center;
    font-family: Source Han Sans CN;
    font-size: 16px;
    font-style: normal;
    font-weight: 400;
    line-height: normal;
  }
  // 上一年图标
  .fc-icon-chevron-left {
    color: var(--text-color);
  }
  // 上个月图标
  .fc-icon-chevrons-left {
    color: var(--text-color);
  }
  // 下一年图标
  .fc-icon-chevrons-right {
    color: var(--text-color);
  }
  // 下个月图标
  .fc-icon-chevron-right {
    color: var(--text-color);
  }
  .fullcalendar-radius {
    border-top-right-radius: 0.95rem;
    border-bottom-right-radius: 0.95rem;
  }
}

.schedules-single {
  display: inline-block;
  font-size: 10px;
  margin-top: 20%;
}
.schedules-circle {
  width: 8px;
  height: 8px;
  border-radius: 8px;
  background: #00bd7e;
  display: inline-block;
  margin-right: 4px;
}
.schedules {
  display: inline-block;
  font-size: 12px;
  width: 100%;
  height: 25px;
  border-color: rgb(255, 153, 153);
  background-color: rgb(255, 211, 211);
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 5px;
  margin-top: 20%;
}
.ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.purple {
  background-color: rgb(179, 127, 235);
}
.blue {
  background: #409eff;
}
.green {
  background-color: #67c23a;
}
.red {
  background-color: #f56c6c;
}
.yellow {
  background-color: #e6a23c;
}
.info {
  background-color: #909399;
}
</style>
